package ar.com.sebasoft.rembrandt.adapter;

import java.text.DateFormat;
import java.util.List;

import org.holoeverywhere.widget.ArrayAdapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v4.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import ar.com.sebasoft.rembrandt.R;
import ar.com.sebasoft.rembrandt.model.Foto;
import ar.com.sebasoft.rembrandt.util.SystemHelper;

import com.androidquery.AQuery;
import com.androidquery.callback.BitmapAjaxCallback;
import com.androidquery.util.Constants;

/**
 * @author SebaSOFT
 *
 */
public class FotoAdapter extends ArrayAdapter<Foto> {

	private List<Foto> mList;

	private static LruCache<String, Bitmap> bMapCahce = new LruCache<String, Bitmap>(100);

	public FotoAdapter(Context context, List<Foto> objects) {
		super(context, R.layout.li_album_item, objects);
		this.setNotifyOnChange(true);
		this.mList = objects;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View row;
		LayoutInflater listInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		if (null == convertView) {
			row = listInflater.inflate(R.layout.li_photo_thumb, null);
		} else {
			row = convertView;
		}
		row.setTag(this.getItem(position));

		this.populateView(row, this.getItem(position));

		return row;
	}

	private void populateView(View row, Foto item) {
		AQuery aq = new AQuery(row);

		// Obtenemos la diapositiva de la cache
		Bitmap thumb = bMapCahce.get(item.getPath());

		if (thumb != null) {
			aq.id(R.id.photoThumb).image(thumb);
		} else {
			Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(this.getContext().getContentResolver(), item.getImgID(), MediaStore.Images.Thumbnails.MICRO_KIND, null);
			if (bitmap != null) {
				bMapCahce.put(item.getPath(), bitmap);

				// create a bitmap ajax callback object
				BitmapAjaxCallback cb = new BitmapAjaxCallback();

				// configure the callback
				cb.bitmap(bitmap).fallback(R.drawable.ic_no_image).animation(Constants.FADE_IN);

				// invoke it with an image view
				aq.id(R.id.photoThumb).image(cb);
			} else {
				aq.id(R.id.photoThumb).image(R.drawable.ic_no_image);
			}
		}

		if (item.getTitulo() != null) {
			aq.id(R.id.photoTitle).text(item.getTitulo());
		} else {
			aq.id(R.id.photoTitle).text(SystemHelper.getLocalizedString(R.string.msg_no_name));
		}
		if (item.getFecha() != null) {
			aq.id(R.id.photoDate).text(DateFormat.getDateInstance(DateFormat.SHORT).format(item.getFecha()));
		} else {
			aq.id(R.id.photoDate).text(SystemHelper.getLocalizedString(R.string.msg_no_date));
		}
	}

	/**
	 * @return the mList
	 */
	public final List<Foto> getmList() {
		return this.mList;
	}

	public void clearCache() {
		bMapCahce.evictAll();
	}
}
